package com.atguigu.gmall.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.IpUtil;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserService;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author Fxz
 * @version 1.0
 * @date 2022-02-15 14:24
 */
@SuppressWarnings("all")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/user/passport")
public class PassportApiController {

	private final UserService userService;

	private final RedisTemplate redisTemplate;

	@PostMapping("/login")
	public Result login(@RequestBody UserInfo userInfo, HttpServletRequest request) {
		UserInfo login = userService.login(userInfo);
		Map<String, Object> map = new HashMap<>();
		if (ObjectUtils.isNotEmpty(login)) {
			String token = "FXZ_" + UUID.randomUUID();
			map.put("token", token);
			map.put("nickName", login.getName());
			String userKey = RedisConst.USER_LOGIN_KEY_PREFIX + token;
			String ip = IpUtil.getIpAddress(request);
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("userId", login.getId());
			jsonObject.put("ip", ip);
			redisTemplate.opsForValue().set(userKey, jsonObject.toJSONString(), RedisConst.USER_CART_EXPIRE,
					TimeUnit.SECONDS);
			return Result.ok(map);
		}
		return Result.fail().message("登陆失败!");
	}

	@GetMapping("/logout")
	public Result logout(HttpServletRequest request) {
		String token = request.getHeader("token");
		String userKey = RedisConst.USER_LOGIN_KEY_PREFIX + token;
		this.redisTemplate.delete(userKey);
		return Result.ok();
	}

}
